package com.seadragon.app.ksr.service.impl;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.seadragon.app.ksr.dao.ReviewDao;
import com.seadragon.app.ksr.model.Customer;
import com.seadragon.app.ksr.model.Office;
import com.seadragon.app.ksr.model.Review;
import com.seadragon.app.ksr.service.OfficeService;
import com.seadragon.app.ksr.service.ReviewService;
import com.seadragon.app.ksr.util.IndexManager;

@Service("reviewService")
@Transactional
public class ReviewServiceImpl implements ReviewService {
	private static Logger logger = LoggerFactory.getLogger(ReviewServiceImpl.class);
	@Autowired
	private ReviewDao reviewDao;
	
	@Autowired
	private OfficeService officeService;
	
	@Autowired
	private IndexManager indexManager;
	
	@Override
	public void save(Review review){
		officeService.update(review.getOffice(), review);

		Review savedReview = reviewDao.save(review);
		
		try{
			indexManager.insertDocument(savedReview.getOffice());
			indexManager.insertDocument(savedReview);
		}catch(Exception ex){
			logger.error(ex.getMessage(), ex);
		}
	}
	
	@Override
	public List<Review> findByOffice(Office office) {
		return reviewDao.findByOffice(office);
	}
	
	@Override
	public long count(Office office){
		return reviewDao.count(office);
	}

	@Override
	public List<Review> findByCustomer(Customer customer) {
		return reviewDao.findByCustomer(customer);
	}

	@Override
	public List<Review> findByOfficeAndReview(Office office, int reviewRating) {
		return reviewDao.findByOfficeAndReview(office, reviewRating);
	}

	@Override
	public List<Review> findByCustomerAndReview(Customer customer, int reviewRating) {
		return reviewDao.findByCustomerAndReview(customer, reviewRating);
	}

	@Override
	public void update(Review review) {
		officeService.update(review.getOffice(), review);
		reviewDao.update(review);
		try{
			indexManager.insertDocument(review.getOffice());
			indexManager.insertDocument(review);
		}catch(Exception ex){
			logger.error(ex.getMessage(), ex);
		}

	}

	@Override
	public List<Review> findAll(int offset, int pageSize) {
		return reviewDao.findAll(offset, pageSize);
	}
}
